import Message from '@/utils/message';
import styled from '@emotion/styled';
import React, { useEffect } from 'react';
const Video = styled.video``;
import { useTranslation } from 'react-i18next';

interface VideoProps {
	streamId: string;
	irtcClient: any;
	setRenderTTSStream: (stream: any) => void;
	renderTTSStream: any[];
	stream: any;
}

const TTSVideoItem = (props: VideoProps) => {
	const { t } = useTranslation();
	const { streamId, irtcClient, setRenderTTSStream, renderTTSStream, stream } = props;

	useEffect(() => {
		if (renderTTSStream.find((ele: any) => ele.id === streamId)) {
			renderTTSStream.forEach((item: any) => {
				if (item.id === streamId) {
					let video = document.getElementById(streamId) as HTMLVideoElement;
					video!.srcObject = item.mediaStream;
					video!.play();
				}
			});
			return;
		}
		substream(stream);
	}, [streamId]);

	/*订阅当前房间里面的流*/
	const substream = (stream: any) => {
		console.log('开始订阅', stream, stream.settings);
		//判断流的source
		let audio = true;
		let video = true;
		if (!stream.settings.audio) {
			audio = false;
		}
		if (!stream.settings.video) {
			video = false;
		}
		let options = {
			audio: audio,
			video: video
		};
		console.log(irtcClient, options, stream);
		irtcClient.subscribe(stream, options).then(
			(subscription: any) => {
				console.log(subscription, '订阅成功', stream.id, stream);
				setRenderTTSStream([...renderTTSStream, stream]);
				let video = document.getElementById(stream.id) as HTMLVideoElement;
				video!.srcObject = stream.mediaStream;
			},
			(err: any) => {
				const subscription = t('subscription');
				const failed = t('failed');
				Message.error(`${subscription}${stream.id}${failed}`);
				console.log('subscribe failed');
				console.log(`subscribe ${stream.id} failed: ${err}`);
			}
		);
	};
	return (
		<div>
			<Video x5-video-player-type="h5" controlsList="nodownload nofullscreen" playsInline autoPlay id={streamId}></Video>
		</div>
	);
};

export default TTSVideoItem;
